﻿/*
* 作 者: 槐尧
* 创建时间: 2016/1/2 13:42:57
* 说明:  
*/

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;

class ExcelToolEditor : EditorWindow
{
    const int AreaHeight = 30;
    List<Dictionary<string, string>> lstDic = new List<Dictionary<string, string>>();

    [MenuItem("Editor/ExcelToolEditor")]
    static void AddWindow()
    {
        //创建脚本生成的目录
        string scriptDirectory = Application.dataPath + "/Scripts/Killer/DataConfig/ProtoGen";
        if (!Directory.Exists(scriptDirectory))
        {
            Directory.CreateDirectory(scriptDirectory);
        }

        string configDirectory = Application.streamingAssetsPath + "/DataConfig";
        if (!Directory.Exists(configDirectory))
        {
            Directory.CreateDirectory(configDirectory);
        }
        
        //创建窗口
        Rect wr = new Rect(0, 0, 500, 800);
        ExcelToolEditor window = (ExcelToolEditor)EditorWindow.GetWindowWithRect(typeof(ExcelToolEditor), wr, true, "ExcelTool");
        window.lstDic.Clear();

        string configPath = Application.streamingAssetsPath + "/DataConfig/DataConfig.txt";
        if (!File.Exists(configPath))
        {
            List<object> lst = new List<object>();
            Dictionary<string, object> dc = new Dictionary<string, object>();
            dc["ExcelName"] = "";
            dc["ClassName"] = "";
            lst.Add(dc);
            ClassCreateHelper.CreateFile(configPath, Json.Serialize(lst));
            Debug.LogError("请首先在StreamingAssets/DataConfig目录下配置文件");
            AssetDatabase.Refresh();
        }
        string content = File.ReadAllText(configPath);
        List<object> lstObj = Json.Deserialize(content) as List<object>;

        foreach (object o  in lstObj)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Dictionary<string, object> kv = o as Dictionary<string, object>;
            dic["ExcelName"] = kv["ExcelName"].ToString();
            dic["ClassName"] = kv["ClassName"].ToString();

            window.lstDic.Add(dic);
        }
        window.Show();
    }

    //绘制窗口时调用
    void OnGUI()
    {
        for (int index = 0; index < lstDic.Count; index++)
        {
            GUILayout.BeginArea(new Rect(10, 20 + AreaHeight * index, 500, 250));
            Dictionary<string, string> dic = lstDic[index];
            string excelName = dic["ExcelName"];
            string className = dic["ClassName"];
            DrawExcelInfo(excelName, className);
            GUILayout.EndArea();
        }
    }

    void DrawExcelInfo(string excelName,string className)
    {
        EditorGUILayout.LabelField("文件:" + excelName);
        bool attackBtn = GUI.Button(new Rect(250, 0, 100, 20), "生成");

        if (attackBtn)
        {
            ClassCreateHelper.CreateCsFile(excelName, className);
            ProcessBat.create(excelName, className);
            
        }
    }
}
